package com.yuanheng100.ems4j.web;

import com.yuanheng100.ems4j.web.utils.ConfigFile;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

import java.io.File;

/**
 * Jetty启动类
 */
public class WebLauncher
{
    private static final Logger log = Logger.getLogger(WebLauncher.class);

    private static final String PORTSTR = ConfigFile.getProperty("system.web.port");
    private static final String CONTEXT_PATH = ConfigFile.getProperty("system.web.context.path"); // 项目名称
    private static final String PROJECT_PATH = ClassLoader.getSystemClassLoader().getResource("").getPath();
    //private static final String GLOBAL_XML_PATH = PROJECT_PATH + File.separatorChar + "conf" + File.separatorChar + "web.xml";
    private static final String WEB_APP_PATH = PROJECT_PATH + File.separatorChar + "webapp";
    private static final String TEMP_PATH = PROJECT_PATH + File.separatorChar + "temp";
    private static final String WORK_PATH = PROJECT_PATH + File.separatorChar + "work";

    private Server server = new Server(Integer.parseInt(PORTSTR));

    public void start()
    {
        log.info("Jetty starting...");

        WebAppContext context = new WebAppContext(WEB_APP_PATH, CONTEXT_PATH);
        context.setDescriptor(WEB_APP_PATH + "/WEB-INF/web.xml");
        //context.setResourceBase(WEB_APP_PATH);
        //context.setContextPath(CONTEXT_PATH);
        context.setTempDirectory(new File(TEMP_PATH));
        context.setParentLoaderPriority(true);
        context.setClassLoader(Thread.currentThread().getContextClassLoader());

        server.setHandler(context);
        try
        {
            server.start();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        log.info("Jetty started.");
        /*try
        {
            server.join();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }*/
    }

    public void stop() throws Exception
    {
        log.info("Jetty stopping...");
        server.stop();
        server.destroy();
        log.info("Jetty stoped");
    }
}
